package com.jhgsys.internal.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jhgsys.internal.base.constant.BaseConstants;
import com.jhgsys.internal.base.entity.BaseGoods;
import com.jhgsys.internal.base.service.IBaseGoodsService;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.base.dto.BaseGoodsInventoryRecordDto;
import com.jhgsys.internal.base.entity.BaseGoodsInventoryRecord;
import com.jhgsys.internal.base.mapper.BaseGoodsInventoryRecordMapper;
import com.jhgsys.internal.base.service.IBaseGoodsInventoryRecordService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 安全奖品库存记录 Service实现
 *
 * @author admin
 * @date 2024-08-06 09:41:00
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class BaseGoodsInventoryRecordServiceImpl extends ServiceImpl<BaseGoodsInventoryRecordMapper, BaseGoodsInventoryRecord> implements IBaseGoodsInventoryRecordService {

    @Autowired
    private IBaseGoodsService baseGoodsService;

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-08-06 09:41:00
     * @param request QueryRequest
     * @param baseGoodsInventoryRecord baseGoodsInventoryRecord
     * @return IPage<BaseGoodsInventoryRecord>
    */
    @Override
    public IPage<BaseGoodsInventoryRecord> findBaseGoodsInventoryRecordPage(QueryRequest request, BaseGoodsInventoryRecordDto baseGoodsInventoryRecord) {
        LambdaQueryWrapper<BaseGoodsInventoryRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseGoodsInventoryRecord::getDeletedFlg, FebsConstant.VALID);

        if(StringUtils.isNotBlank(baseGoodsInventoryRecord.getTenantId())){
            queryWrapper.eq(BaseGoodsInventoryRecord::getTenantId, baseGoodsInventoryRecord.getTenantId());
        }

        if(StringUtils.isNotBlank(baseGoodsInventoryRecord.getGoodsName())){
            queryWrapper.like(BaseGoodsInventoryRecord::getGoodsName,baseGoodsInventoryRecord.getGoodsName());
        }
        if(StringUtils.isNotBlank(baseGoodsInventoryRecord.getOperateType())){
            queryWrapper.like(BaseGoodsInventoryRecord::getOperateType,baseGoodsInventoryRecord.getOperateType());
        }
        if(StringUtils.isNotBlank(baseGoodsInventoryRecord.getStartDate()) && StringUtils.isNotBlank(baseGoodsInventoryRecord.getEndDate()) ){
            Date startDate = DateUtil.parseDate(baseGoodsInventoryRecord.getStartDate()+DateUtil.START_DATA_PATTERN,DateUtil.FULL_TIME_SPLIT_PATTERN);
            Date endDate = DateUtil.parseDate(baseGoodsInventoryRecord.getEndDate()+DateUtil.END_DATA_PATTERN,DateUtil.FULL_TIME_SPLIT_PATTERN);
            queryWrapper.between(BaseGoodsInventoryRecord::getCreatedTime,startDate,endDate);
        }
        queryWrapper.orderByDesc(BaseGoodsInventoryRecord::getCreatedTime);

        Page<BaseGoodsInventoryRecord> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询（分页）dto增强返回
     * @author admin
     * @date 2024-08-06 09:41:00
     * @param request QueryRequest
     * @param baseGoodsInventoryRecord baseGoodsInventoryRecord
     * @return IPage<BaseGoodsInventoryRecordDto>
     */
    @Override
    public IPage<BaseGoodsInventoryRecordDto> findBaseGoodsInventoryRecordDtoPage(QueryRequest request, BaseGoodsInventoryRecordDto baseGoodsInventoryRecord) {
        IPage<BaseGoodsInventoryRecordDto> dtoPage = new Page<>();
        IPage<BaseGoodsInventoryRecord> page = this.findBaseGoodsInventoryRecordPage(request, baseGoodsInventoryRecord);
        List<BaseGoodsInventoryRecord> records = page.getRecords();
        List<BaseGoodsInventoryRecordDto> dtoList = BeanHelper.copyWithCollection(records,BaseGoodsInventoryRecordDto.class);
        if(!CollectionUtils.isEmpty(records)) {
            List<BaseGoods> goodsList = baseGoodsService.list(new LambdaQueryWrapper<BaseGoods>()
                    .eq(BaseGoods::getDeletedFlg, FebsConstant.VALID)
                    .in(BaseGoods::getGoodsId, records.stream().map(BaseGoodsInventoryRecord::getGoodsId).collect(Collectors.toList())));

            dtoList.forEach(item -> {
                BaseGoods goods = goodsList.stream().filter(g -> g.getGoodsId().equals(item.getGoodsId())).findFirst().get();
                item.setSmallPath(goods.getSmallPath());
                item.setFilePath(goods.getFilePath());
            });
            dtoPage.setRecords(dtoList);
            dtoPage.setTotal(page.getTotal());
        }
        return dtoPage;
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-08-06 09:41:00
     * @param baseGoodsInventoryRecord baseGoodsInventoryRecord
     * @return List<BaseGoodsInventoryRecord>
     */
    @Override
    public List<BaseGoodsInventoryRecord> findBaseGoodsInventoryRecordList(BaseGoodsInventoryRecord baseGoodsInventoryRecord) {
	    LambdaQueryWrapper<BaseGoodsInventoryRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseGoodsInventoryRecord::getDeletedFlg, FebsConstant.VALID);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author admin
    * @date 2024-08-06 09:41:00
    * @param id
    * @return BaseGoodsInventoryRecord
    */
    @Override
    public BaseGoodsInventoryRecord findBaseGoodsInventoryRecordById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author admin
     * @date 2024-08-06 09:41:00
     * @param baseGoodsInventoryRecord baseGoodsInventoryRecord
     */
    @Override
    @Transactional
    public void createBaseGoodsInventoryRecord(BaseGoods goods,BaseGoodsInventoryRecord baseGoodsInventoryRecord) {
        int afterInventory = goods.getInventory();
        if(BaseConstants.GOODS_OPERATE_TYPE.IN.equals(baseGoodsInventoryRecord.getOperateType())){
            afterInventory += baseGoodsInventoryRecord.getOperateNumber();
        }else {
            afterInventory -= baseGoodsInventoryRecord.getOperateNumber();
        }
        //更新商品表库存
        Boolean goodsUpdate = baseGoodsService.update(new LambdaUpdateWrapper<BaseGoods>()
                .eq(BaseGoods::getGoodsId,baseGoodsInventoryRecord.getGoodsId())
                .eq(BaseGoods::getInventory,goods.getInventory())
                .set(BaseGoods::getInventory,afterInventory));

        //更新出入库记录表
        if(goodsUpdate) {
            baseGoodsInventoryRecord.setBeforeNumber(goods.getInventory());
            baseGoodsInventoryRecord.setAfterNumber(afterInventory);
            baseGoodsInventoryRecord.setCreatedTime(new Date());
            baseGoodsInventoryRecord.setGoodsName(goods.getGoodsName());
            this.save(baseGoodsInventoryRecord);
        }

    }

    /**
     * 修改
     * @author admin
     * @date 2024-08-06 09:41:00
     * @param baseGoodsInventoryRecord baseGoodsInventoryRecord
     */
    @Override
    @Transactional
    public void updateBaseGoodsInventoryRecord(BaseGoodsInventoryRecord baseGoodsInventoryRecord) {
        baseGoodsInventoryRecord.setUpdatedTime(new Date());
        this.saveOrUpdate(baseGoodsInventoryRecord);
    }

    /**
     * 逻辑删除
     * @author admin
     * @date 2024-08-06 09:41:00
     * @param baseGoodsInventoryRecord baseGoodsInventoryRecord
     * @param baseGoodsInventoryRecordIds baseGoodsInventoryRecordIds
     */
    @Override
    @Transactional
    public void deleteBaseGoodsInventoryRecord(BaseGoodsInventoryRecord baseGoodsInventoryRecord,String baseGoodsInventoryRecordIds) {
        List<String> list = Arrays.asList(baseGoodsInventoryRecordIds.split(StringPool.COMMA));
        this.baseMapper.update(baseGoodsInventoryRecord,new LambdaQueryWrapper<BaseGoodsInventoryRecord>().in(BaseGoodsInventoryRecord::getGoodsInventoryRecordId,list));
	}

    /**
    * 物理删除
    * @author admin
    * @date 2024-08-06 09:41:00
    * @param baseGoodsInventoryRecordIds baseGoodsInventoryRecordIds
    */
    @Override
    @Transactional
    public void physicallyDeleteBaseGoodsInventoryRecord(String baseGoodsInventoryRecordIds) {
        List<String> list = Arrays.asList(baseGoodsInventoryRecordIds.split(StringPool.COMMA));
        LambdaQueryWrapper<BaseGoodsInventoryRecord> wapper = new LambdaQueryWrapper<>();
        wapper.in(BaseGoodsInventoryRecord::getGoodsInventoryRecordId,list);
        this.remove(wapper);
    }
}
